import { defineStore } from 'pinia'
import { constantRouterMap } from '@/router'
import { formatRoutes, getFirstPath, Layout, flatMultiLevelRoutes } from '@/utils/routerHelper'
import { useCache } from '@/hooks/web/useCache'
import { store } from '../index'
import { cloneDeep } from 'lodash-es'
import { getConfig } from '@/api/basic'
import { getUserInfo, getPermissions } from '@/api/login'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useNotificationStoreWithOut } from '@/store/modules/notification'

const { wsCache } = useCache()
const appStore = useAppStoreWithOut()
const notificationStore = useNotificationStoreWithOut()
export interface PermissionState {
  routers: AppRouteRecordRaw[]
  addRouters: AppRouteRecordRaw[]
  isAddRouters: boolean
  menuTabRouters: AppRouteRecordRaw[]
  token: string
  navigation: Array<any>
  isLoadedConfig: boolean
  firstPath: string
  userInfo: any
  permissions: Array<any>
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routers: [],
    addRouters: [],
    isAddRouters: false,
    menuTabRouters: [],
    token: wsCache.get('Admin-Token') || '',
    navigation: [],
    isLoadedConfig: false,
    firstPath: '',
    userInfo: null,
    permissions: []
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers
    },
    getAddRouters(): AppRouteRecordRaw[] {
      return flatMultiLevelRoutes(cloneDeep(this.addRouters))
    },
    getIsAddRouters(): boolean {
      return this.isAddRouters
    },
    getMenuTabRouters(): AppRouteRecordRaw[] {
      return this.menuTabRouters
    },
    getToken(): string {
      return this.token
    },
    getNavigation(): Array<any> {
      return this.navigation
    },
    getIsLoadedConfig(): boolean {
      return this.isLoadedConfig
    },
    getFirstPath(): string {
      return this.firstPath
    },
    getUserInfo(): any {
      return this.userInfo
    },
    getPermissions(): any {
      return this.permissions
    }
  },
  actions: {
    async fetchConfigs(): Promise<void> {
      const res = await getConfig()
      if (res && res.configs) {
        await this.setNavigation(res.configs.navigation.routes)
        const perRes = await getPermissions({}).catch(() => {})
        this.permissions = perRes?.data || []
        await this.generateRoutes('admin')
        notificationStore.setConfig(res.configs.notification)
      }
    },
    async fetchUserInfo(): Promise<any> {
      const res = await getUserInfo()
      wsCache.set(appStore.getUserInfo, res.data)
      this.userInfo = res.data
      return Promise.resolve(res.data)
    },
    generateRoutes(
      type: 'admin' | 'test' | 'none',
      routers?: AppCustomRouteRecordRaw[] | string[]
    ): Promise<unknown> {
      return new Promise<void>((resolve) => {
        console.log(type, routers)
        let routerMap: AppRouteRecordRaw[] = []

        const routeList = formatRoutes(this.navigation)
        const firstRoute: Array<any> = []
        const firstPath = getFirstPath(routeList.filter((r) => !r.meta.hidden))
        if (firstPath) {
          firstRoute.push({
            path: '/',
            name: 'firstPage',
            component: Layout,
            meta: { hidden: true },
            redirect: firstPath
          })
          this.firstPath = firstPath
        }
        routerMap = [...firstRoute, ...routeList]
        // 动态路由，404一定要放到最后面
        this.addRouters = routerMap.concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: '404Page',
            meta: {
              hidden: true,
              breadcrumb: false
            }
          }
        ])
        // 渲染菜单的所有路由
        this.routers = cloneDeep(constantRouterMap).concat(routerMap)
        resolve()
      })
    },
    setDefaultLogin() {
      const token = 'test'
      this.setToken(token)
      this.userInfo = {
        token: '',
        roles: ['admin'],
        name: 'admin',
        avatar: '',
        introduction: ''
      }
      wsCache.set(appStore.getToken, token)
      wsCache.set(appStore.getUserInfo, this.userInfo)
    },
    setIsAddRouters(state: boolean): void {
      this.isAddRouters = state
    },
    setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
      this.menuTabRouters = routers
    },
    setNavigation(navigation) {
      this.navigation = navigation
    },
    setPermissions(permissions) {
      this.permissions = permissions
    },
    setToken(token: string): void {
      this.token = token
    },
    setIsLoadedConfig(state: boolean): void {
      this.isLoadedConfig = state
    }
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}
